/*
 * @Author: lyztroy lyztroy@bupt.edu.cn
 * @Date: 2021-12-20 14:18:30
 * @LastEditors: lyztroy lyztroy@bupt.edu.cn
 * @LastEditTime: 2022-06-12 14:57:41
 * @FilePath: /visualNotes/src/models/Diagram/index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createModel } from "@rematch/core";
import { SavePayload, initMyDiagramPayload } from "../interface";
import {
  OnLoadParams,
  Elements,
  removeElements,
  FlowElement,
} from "react-flow-renderer";
import type { RootModel } from "../index";
import { db} from "@/service";


interface InitState {
  // 画布实例
  reactFlowInstance?: any;
  // 节点数据、连线数据
  elements?: Elements;
  // 画布数据
  flowData?: Map<any, any>;
  // 弹窗信息
  modalConfig?: {
    visible?: boolean;
    nodeType?: string;
    nodeId?: string;
  };
  allowedNodes?: Array<{ name: string; type: string; images?: string }>;
}

export const diagram = createModel<RootModel>()({
  state: {
    reactFlowInstance: null,
    elements: [],
    flowData: new Map(),
    allowedNodes: [],
    modalConfig: {},
  } as InitState,
  reducers: {
    updateState(state, payload: InitState) {
      return {
        ...state,
        ...payload,
      };
    },
    //保存画布信息
    setFlowInstance(state, reactFlowInstance: OnLoadParams | null) {
      return {
        ...state,
        reactFlowInstance,
      };
    },
    // 设置节点/连线数据
    setElements(state, elements: Elements) {
      return {
        ...state,
        elements: Array.isArray(elements) ? elements : [],
      };
    },
    //保存节点信息
    saveFlowNode  (state: any, node: FlowElement)  {  
      const nodeId = node?.id;    
      const data = node?.data ?? "";    
        
      // Create a new elements array if the nodeId exists  
      const newEl = [...(state.elements || [])].map((item) => {  
        if (item.id === nodeId) {    
          return {    
            ...item,    
            data,    
          };    
        } else {    
          return item;    
        }    
      });    
      
      // Return a new state object with the updated elements array and flowData  
      return {  
        ...state,  
        elements: newEl,  
        flowData: nodeId ? state.flowData?.set(nodeId, node) : state.flowData,  
      };  
    },
     
    saveFlowEdge(state, edge: FlowElement) {  
      const edgeId = edge?.id;  
      const newEl = state.elements?.map((item) => {  
        if (item.id === edgeId) {  
          return {  
            ...item,   
          };  
        } else {  
          return item;  
        }  
      });  
      if (!edgeId) {  
        return {  
          ...state,  
        };  
      } else {  
        return {  
          ...state,  
          flowData: state.flowData?.set(edgeId, edge),  
          elements: newEl,  
        };  
      }  
    },


    //删除节点信息
    removeFlowNode(state, node: FlowElement) {  
      const { id } = node;  
      const { flowData } = state;  
      const res = { ...state };  
      if (flowData?.get(id)) {  
        flowData.delete(id);
        res.elements = removeElements([node], state.elements || []);
      }    
      return { ...res };
    },
    //删除连线信息
    removeFlowEdge(state, edge: FlowElement) {  
      const { id } = edge;  
      const { flowData } = state;  
      const res = { ...state };  
      if (flowData?.get(id)) {  
        flowData.delete(id);  
        res.elements = removeElements([edge], state.elements || []);  
      }  
      return { ...res };  
    },
    //打开弹出框
    openModal(state, node: FlowElement) {
      return node.id
        ? {
            ...state,
            modalConfig: {
              visible: true,
              nodeType: node.type,
              nodeId: node.id,
            },
          }
        : { ...state };
    },
    //关闭弹出框
    closeModal(state) {
      return {
        ...state,
        modalConfig: {
          visible: false,
          nodeType: "",
          nodeId: "",
        },
      };
    },

  },
  effects: (dispatch) => ({
    //根据图的类型初始化左侧工具栏
    initSider(payload: string, state) {
      switch (payload) {
        case "useCase":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "执行者",
                type: "People",
              },
              {
                name: "用例",
                type: "UseCase",
              },
            ],
          });
          break;
        case "category":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "模块",
                type: "ModDefinition",
              },
              {
                name: "结构属性",
                type: "Border",
              },
              {
                name: "行为属性",
                type: "Apply",
              },
            ],
          });
          break;
        case "collaboration":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "功能需求",
                type: "Objects",
              },
              {
                name: "约束框",
                type: "ConstBox",
              },
              {
                name: "方案",
                type: "Scheme",
              },
            ],
          });
          break;
        case "status":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "开始",
                type: "StartPoint",
              },
              {
                name: "结束",
                type: "EndPoint",
              },
              {
                name: "状态",
                type: "StatusNode",
              },
            ],
          });
          break;
          case "parameter":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "约束框",
                type: "ConstBox",
              },
              {
                name: "属性框",
                type: "Border",
              },
            ],
          });
          break;
          case "package":
          dispatch.diagram.updateState({
            allowedNodes: [
              {
                name: "视图",
                type: "View",
              },
              {
                name: "视点",
                type: "ViewPoint",
              },
              {
                name:"包",
                type:"Package",
              },
              {
                name:"模型",
                type:"Model",
              }
            ],
          });
          break;
          case "activity":
            dispatch.diagram.updateState({
              allowedNodes: [
                {
                  name: "开始",
                  type: "StartPoint",
                },
                {
                  name: "决定/合并",
                  type: "Decide",
                },
                {
                  name:"分支/集合",
                  type:"Gather",
                },
                {
                  name: "活动",
                  type: "StatusNode",
                },
                {
                  name: "结束",
                  type: "EndPoint",
                },
              ],
            });
            break;
        case"seq":
        dispatch.diagram.updateState({
          allowedNodes: [
            {
              name: "参与者",
              type: "People",
            },
            {
              name: "模块",
              type: "ModDefinition",
            },
            {
              name: "消息事件",
              type: "Things",
            },
            {
              name: "执行说明",
              type: "Instruction",
            },
          ],
        });
        break;
        case"ibd":
        dispatch.diagram.updateState({
          allowedNodes: [
            {
              name: "组件属性",
              type: "Border",
            },
            {
              name: "引用属性",
              type: "Apply",
            },
          ],
        });
        break;
        default:
          dispatch.diagram.updateState({
            allowedNodes: [],
          });
          break;
      }
    },


 //根据id和type返回用户项目
 async initMyDiagram(payloads: initMyDiagramPayload, state) {  
  const { diagramId} = payloads;
  console.log(diagramId);
  var query=window.location.href;
  var toolID  = query.toString().slice(-8);
  const res=await db.collection("payloads")
  .where(
    {diagramId:toolID}
  ).field({
    type:true,
    elements:true,
    diagramId:true,
    _id:true,
  })
  .get()
  if(res.data[0]){
    dispatch.diagram.updateState({
      elements:res.data[0].elements,
      })
    for(var i of res.data[0].elements){
      if(i.data.label){
        let values:any = {
          label:i.data.label,
          remark:i.data.remark
       }
        dispatch.diagram.saveFlowNode({
         id: i.id,
         ...values,
         data: {
           ...values,
         },
       });
      }   
    }  
  }
  else{
    dispatch.diagram.updateState({
      elements:[],
      })
  }
},
    //保存画布信息
    saveDiagram(payload: SavePayload, state) {
      console.log("payload", payload);
    },
  }),
});
